package com.lewis.common.controller;

import com.lewis.core.config.LewisConfig;
import com.lewis.core.constant.Constants;
import com.lewis.core.base.domain.BaseResult;
import com.lewis.core.utils.MapUtil;
import com.lewis.core.utils.ServletUtil;
import com.lewis.core.utils.StringUtil;
import com.lewis.core.utils.file.FileUploadUtil;
import com.lewis.core.utils.file.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author Lewis
 */
@Api(tags = "通用请求处理")
@RestController
@Slf4j
public class CommonController {

    @GetMapping("common/download")
    @ApiOperation(
            value = "通用下载请求",
            notes = "fileName == 文件名称; delete == 是否删除"
    )
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) {
        try {
            if (!FileUtil.checkAllowDownload(fileName)) {
                throw new Exception(StringUtil.format("文件名称({})非法，不允许下载。 " , fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = LewisConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtil.setAttachmentResponseHeader(response, realFileName);
            FileUtil.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtil.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败" , e);
        }
    }

    @PostMapping("/common/upload")
    @ApiOperation(
            value = "通用上传请求",
            notes = "file == 文件MultipartFile流"
    )
    public Object uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = LewisConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtil.upload(filePath, file);
            HttpServletRequest request = ServletUtil.getRequest();
            StringBuffer urlTest = request.getRequestURL();
            String contextPath = request.getServletContext().getContextPath();
            String urlDomain = urlTest.delete(urlTest.length() - request.getRequestURI().length(), urlTest.length()).append(contextPath).toString();
            String url = urlDomain + fileName;
            BaseResult ok = BaseResult.ok();
            Map<String, Object> ajax = MapUtil.object2MapByReflect(ok);
            ajax.put("fileName" , fileName);
            ajax.put("url" , url);
            return ajax;
        } catch (Exception e) {
            return BaseResult.fail().setMsg(e.getMessage());
        }
    }

    @GetMapping("/common/download/resource")
    @ApiOperation(
            value = "本地资源通用下载",
            notes = "resource == 资源路径"
    )
    public void resourceDownload(String resource, HttpServletResponse response) {
        try {
            if (!FileUtil.checkAllowDownload(resource)) {
                throw new Exception(StringUtil.format("资源文件({})非法，不允许下载。 " , resource));
            }
            // 本地资源路径
            String localPath = LewisConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtil.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtil.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtil.setAttachmentResponseHeader(response, downloadName);
            FileUtil.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败" , e);
        }
    }
}
